;( function () {
    "use strict";
   	var param_map = Result.getLocationParamObject();
    var quCode = null;
    var global_param_map;
    
    $( function () {
    	App.init();
		if(!App.checkLogin()){
			 alert("还没有登录");
			 setTimeout(function () {
				Result.forward("../login/login.html", {});
	 		 }, 800);
			 return;
		}
		global_param_map = App.getCookeData();
		initCity();
		
    	loadUserDetail();
    	loadzhishengDou();
    	
    	$("#quzhifu").click(function(){
    		 var order_no = $("#input_order").val();
    		 var type = $("div.payitem.active").attr("type");
			 var channel_type = 0;
			 if(type == "weixin"){
				 channel_type = 2;
			 } else if (type == "zhifubao") {
				 zhifubaoZhifu(order_no);
			 } else if (type == "yihang") {
				 
			 }
			 //zhifuqu(order_no, channel_type);
    		//alert("去第三方平台支付,order_no=" + order_no);
    		//onclick="$('#pay-modal').modal('close')"
    	});
	});
    
    
    function zhifubaoZhifu(order_no){
		//做加密
    	var fee = $("#input_fee").val();
     	var timeStamp = new Date().getTime().toString();
     	var params = {};
     	params.sign = encodeURIComponent(DES3.encrypt("x/fBeYXQ95Q+Aa7QGYVigzRD",hex_md5(timeStamp).toUpperCase()));
     	params.timestamp =timeStamp;
     	var token =$.cookie(App.getCookieTokenEncrypt());
 		if(typeof(token) === "undefined" || token == null || token == "" || token == "null"){
 			//extParams.token = "";
 		} else {
 			params.token = token;
 		}
 		params.imsi = 'unkown';
 		params.imei = 'unkown';
 		params.system_type = '3';
 		params.client_version = 'unkown';
 		params.longitude = 'unkown';
 		params.latitude = 'unkown';
 		params.model = 'unkown';
 		params.channel_type = 'unkown';
 		params.system_version = '3';
 		params.cp_order = order_no;
 		params.cp_type = 1;
 		params.total_original_fee = fee;
 		params.total_real_fee = fee;
 		params.goods_name = "智胜豆充值";
 		params.goods_detail = "购买智胜豆";
 		params.is_page = 1;
 		params.pay_channel_type = 1;
 		$('#pay-modal').modal('close');
 		layer.confirm('正在支付中？', {
 			btn: ['已完成支付','支付出现问题'] //按钮
		}, function(){
			window.location.reload();
		}, function(){
			alert("请尝试重新支付或联系管理员");
		});
 		var str = buildQuery(params);
 		var url = Interface.host.zhisheng_api_host_servser + "pay/getPayCertify?" + str;
 		window.open(url);
	 };
	 
	 
	 
	 /**
	  * 生成get标签
	  */
	 function buildQuery(obj){
		var index;
		var query = "";
		for (index in obj){
			query += (index +"=" + obj[index] + "&");
		}
		query = query.substr(0, query.length-1);
		return query;
	 }
    
    
    function zhifuqu(order_no, channel_type){
    	var fee = $("#input_fee").val();
		 var params = {};
		 params.cp_order = order_no;
		 params.channel_type = channel_type;
		 params.cp_type = 2;
		 params.total_original_fee = fee;
		 params.total_real_fee = fee;
		 params.goods_name = "智胜豆充值";
		 params.goods_detail = "购买智胜豆";
		 console.log(params);
		 alert("调用payGetPayCertify接口");
		 return;
		 Result.doResult( {
			 url:  Interface.zs.payGetPayCertify,
			 data: params,
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			 
			 
		 }, function ( desc ) {
			 Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
		 
	 }
	 
    
    function initCity(){
		 loadByIp();
		 //定位的
		 var cityJson = App.getCity();
		 if(cityJson){
			 $("#local_city").attr("org_code", cityJson.org_code);
			 $("#local_city").attr("org_name", cityJson.org_name);
			 $("#local_city").find("a").html(cityJson.org_name);
			 $("#local_city").removeClass("yes").addClass("yes");
		 } else {
			 $("#local_city").find("a").html("没定位到城市");
			 $("#local_city").removeClass("yes");
		 }
		 //用户正在用的cit
		 var useCityJson = App.getUseCity();
		 if(useCityJson){
			 quCode = useCityJson.org_code;
			 $("#chengshi").html(useCityJson.org_name);
		 }
		 loadAllCity();
		 if(useCityJson){
			 $(".citylist li.yes").removeClass("active");
			 var len = $(".citylist").find("li[org_code="+quCode+"]").length;
			 if(len == 1){
				 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
			 } else if (len > 1) {
				 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
			 }
		 }
	 }
	 
	 function loadUserDetail(){
		 Result.doResult( {
			 url:  Interface.zs.ucGetUserInfoById,
			 data: {"userId" : global_param_map["id"]},
			 type: "POST",
		 }, function ( data ) {
			 $("#_user_name").html(data["nickname"]);
			 if(data["user_icon"] != null && data["user_icon"] != ""){
				 $("#_head_pic").attr("src", Interface.image.pre + data["user_icon"]);
				 $("#my_head").attr("src", Interface.image.pre + data["user_icon"]);
			 }
			 $("#my_name").html(data["nickname"]);
			 $("#my_phone").html(data.mobile);
			 $("#zhishengdou").html(data.zs_bean == null ? 0 : data.zs_bean);
			 $("#zhishengzhan").html(data.zs_diamond == null ? 0 : data.zs_diamond);
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 
	 function loadzhishengDou(){
		 Result.doResult( {
			 url:  Interface.zs.ucQryBeanOfferList,
			 data: {},
			 type: "POST",
		 }, function ( data ) {
			 //banner
			 var $template = $( "#template" ),
			 	$bean_list = $("#bean_list");
			 $bean_list.empty();
			 if( $.isArray( data ) ) {
				 for( var i = 0, l = data.length; i < l; i++ ) {
					 var obj = $template.clone().removeAttr( "id" );
					 if(i == (l-1)){
						 obj.addClass("am-u-end");
					 }
					 var classA = "";
					 if(data[i].bean_num <= 30){
						 classA = 'icon-person-dou-1';
					 } else if (data[i].bean_num <= 90) {
						 classA = 'icon-person-dou-2';
					 } else if (data[i].bean_num <= 300){
						 classA = 'icon-person-dou-3';
					 } else if (data[i].bean_num <= 500){
						 classA = 'icon-person-dou-4';
					 } else if (data[i].bean_num <= 1000){
						 classA = 'icon-person-dou-5';
					 } else if (data[i].bean_num <= 3000){
						 classA = 'icon-person-dou-6';
					 }
					 obj.find("i.icon-person-dou").addClass(classA);
					 $bean_list.append( Result.fillData(obj , data[i], "field" ) );
	             }
			 }
			 init();
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 function init(){
		 $("#bean_list").find(".tozhifu").off().click(function(){
			 var fee = $(this).attr("bean_fee");
			 var params = {};
			 params.userId = global_param_map["id"];
			 params.beanInfoId = $(this).attr("taocan_id");
			 params.orgCode = quCode;
			 Result.doResult( {
				 url:  Interface.zs.ucZsBeanOrder,
				 data: params,
				 type: "POST",
				 async: false,
			 }, function ( data ) {
				 var order_no = data;
				 $("#xu_fee").html(fee);
				 $("#input_order").val(order_no);
				 $("#input_fee").val(fee);
				 $('#pay-modal').modal({'closeViaDimmer':0,'width':760,'height':'488'});
			 }, function ( desc ) {
		       Result.alert( "对不起:" + desc );
			 }, function ( err ) {
				 Result.alert( "错误:" + JSON.stringify(err));
			 } );
			 
		 });
		 
	 }
	 
	 window.replaceBeanFee = function ( $field, fee, rowVal ) {
		$field.html(fee);
	 };
	 
	 window.replaceBeanId = function ( $field, fee, rowVal ) {
		$field.attr("taocan_id", rowVal['id']);
		$field.attr("bean_order", rowVal['bean_order']);
		$field.attr("bean_num", rowVal['bean_num']);
		$field.attr("bean_fee", rowVal['bean_fee']);
	 };
	 
	 
	 $("#city-modal").on("focus", "#search_city", function(){
		 var that = $(this);
		 Result.doResult( {
	    	url: Interface.zs.orgGetOrgList,
	       	type: "POST",
	       	async: false,
	       	data : {}
	   	}, function ( data) {
	   		that.autocomplete(data , {  
	   			minChars: 0,
	   	        width: 680,
	   	        autoFill: false,
	            matchContains: true,  
	            highlight : false,
	            scroll : true, // 当结果集大于默认高度时是否使用卷轴显示  
	            formatItem: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatMatch: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatResult: function(row) {
	                return row.org_name;  
	            }  
	        }).result(function(event, row, formatted) {
	        	$(".citylist li.yes").removeClass("active");
	        	quCode = row.org_code;
            	var org_name = row.org_name;
				$("#chengshi").html(org_name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : org_name};
  			  	App.setUseCity(jj);
  			  	
				var len = $(".citylist").find("li[org_code="+quCode+"]").length;
				 if(len == 1){
					 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
				 } else if (len > 1) {
					 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
				 }
            });  
	   	}, function ( desc ) {
	        Result.alert( "对不起:" + desc );
	    }, function ( err ) {
	        Result.alert( "错误:" + JSON.stringify(err));
	    } );
	 });
	 
	 
	 
	 function loadAllCity(){
		var $list = $("#all_city_list"),
			$template = $("#all_city_template");
			$("#host_city").empty();
		Result.doResult( {
        	url: Interface.zs.orgGetOrgList,
           	type: "POST",
           	async: false,
           	data : {}
       	}, function ( data) {
	       	var letterMap = {
	       		"A" : [], "B" : [], "C" : [], "D" :[],  "E" : [], "F" : [], "G" : [], "H" : [],
	       		"I" : [], "J" : [], "K" : [], "L" : [], "M" : [], "N" : [], "O" : [],
	       		"P" : [], "Q" : [], "R" : [], "S" : [], "T" : [], "U" : [], "V" : [],
	       		"W" : [], "X" : [], "Y" : [], "Z" : []
	       	};
	       	if( $.isArray( data ) ) {
	    		for( var i = 0, l = data.length; i < l; i++ ) {
	    			var temp = data[i]["first_letter"].toUpperCase();
	    			letterMap[temp].push(data[i]);
	            }
	    	   for(var i in letterMap){
	    		  var letterList = letterMap[i];
	    		  if(letterList.length == 0){
	    			  continue;
	    		  }
	    		  var obj = $template.clone().removeAttr( "id" );
	    		  obj.find(".letter_fist").html(i);
	    		  obj.find(".citylist").empty();
	    		  for( var j = 0, l = letterList.length; j < l; j++ ) {
	    			  var org_name = letterList[j]['org_name'];
	    			  //填补hot
	    			  if(letterList[j]['is_hot'] == 1){
	    				  var ah = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
		    			  	+org_name+'</a></li>';
	    				  $("#host_city").append(ah);
	    			  }
	    			  
	    			  //当定位没有订到的话，默认一个已开通的城市
	    			  var active = "";
	    			  if(quCode == null || quCode == ""){
	    				  $("#chengshi").html(org_name);
		    			  quCode = letterList[j]['org_code'];
		    			  active = "active";
		    			  //设置默认的缓存
		    			  var jj = {"org_code" : quCode, "org_name" : org_name};
		    			  App.setUseCity(jj);
		    		  }
	    			  var a = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
	    			  	+org_name+'</a></li>';
	    			  obj.find(".citylist").append(a);
	    			  
		          }
	    		  $list.append(obj);
	    	   }
	        }
	       	
	        $(".citylist li.yes").off().click(function(){
		       	 $(".citylist li.yes").removeClass("active");
		       	 $(this).addClass("active");
	        });
	       	
			$("#btn-city-center").on("click",function(){
				var active =  $(".citylist li.active"),
					name = active.attr("org_name"),
					code = active.attr("org_code");
				quCode = code;
				$("#chengshi").html(name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : name};
  			  	App.setUseCity(jj);
			});
	       	
       	}, function ( desc ) {
            Result.alert( "对不起:" + desc );
        }, function ( err ) {
            Result.alert( "错误:" + JSON.stringify(err));
        } );
	 }
	 
	 
	 
	 window.forwardMyRace = function(){
		 Result.forward("myRace.html", {});
	 };
	 window.forwardCollection = function(){
		 Result.forward("collection.html", {});
	 };
	 window.forwardPerson = function(){
		 Result.forward("person.html", {});
	 };
	 
	 window.forwardMessage = function(){
		 Result.forward("message.html", {});
	 };
	 
	 
	 
	
}( window ) );
